const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({headless: true, args: ['--no-sandbox']});
  const page = await browser.newPage();
  await page.emulate({
                 viewport: { width: 1920, height: 1080 },
                 userAgent:
                   'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'
               });
  const url = "https://www.baidu.com/";
  await page.goto(url, {waitUntil: ['domcontentloaded', 'networkidle0']});
  //当发生页面js代码没有捕获的异常时触发。
  page.on('pagerror', () => {})
  // 当页面崩溃时触发。
  page.on('error', () => {})
  
  await page.focus('#kw');
  await page.type('#kw', "首都");
  await page.click('#su');
  await page.waitForXPath('/html/body/div[1]/div[5]/div[1]/div[2]/div/div[2]/span', {visible: true});
  const html = await page.evaluate(() => {
    return document.querySelector('html').innerHTML;
	});
  const pageWidth =  await page.evaluate(function(){return document.body.scrollWidth;});
  const pageHeight =  await page.evaluate(function(){return document.body.scrollHeight;});
  console.log("html ", html);
  await page.pdf({path: "example.pdf", format: "A2", printBackground: true, margin:{top: "2cm", bottom: "2cm"}});

  await browser.close();
})();
